﻿
using CoreSoft.Frame.Entity;
using CoreSoft.Frame.Entity.http;
using U8API.Pub;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UFIDA.U8.MomServiceCommon;

namespace U8API.Plugin
{
    /// <summary>
    /// 销售发货退货单
    /// </summary>
    public class SaleOrderPlugin
    {
        public string constr = "";
        private string url = "";


        /// <summary>
        /// 弃审事件
        /// </summary>
        /// <param name="domhead"></param>
        /// <param name="dombody"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public bool Delete_After(ref MSXML2.IXMLDOMDocument2 domhead, ref MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            try
            {

                MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

                //从上下文获取U8Login对象
                U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
                if (login != null)
                    constr = login.UFDataConnstringForNet;

                if (string.IsNullOrEmpty(constr))
                {
                    errMsg = "SaleOrderPlugin，Update_After，获取连接串失败";
                    DebugWriteLog.WriteLine("SaleOrderPlugin", "Update_After", errMsg);
                    return false;
                }
                string accid = login.get_cAcc_Id();
                MSXML2.IXMLDOMNode tmphead = domhead.selectSingleNode("//z:row");

                int id = Convert.ToInt32(tmphead.attributes.getNamedItem("id").nodeValue);//入库单号             


                Dictionary<string, string> js;
                js = GetCustDic(accid, id, 1);
                if (js == null)
                {
                    return true;
                }


                var result = HttpHelper.PostDataToServerDic(url, js, "application/x-www-form-urlencoded");
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    DebugWriteLog.WriteLine("SaleOrderPlugin", "Delete_After", errMsg);
                    return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("SaleOrderPlugin", "Delete_After", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }



        /// <summary>
        /// 新增保存时调用PLM接口
        /// </summary>
        /// <param name="domhead"></param>
        /// <param name="dombody"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public bool Insert_Before_plm(ref MSXML2.IXMLDOMDocument2 domhead, ref MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            try
            {

                MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

                //从上下文获取U8Login对象
                U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
                if (login != null)
                    constr = login.UFDataConnstringForNet;

                if (string.IsNullOrEmpty(constr))
                {
                    errMsg = "SaleOrderPlugin,Insert_After_plm,获取连接串失败";
                    DebugWriteLog.WriteLine("SaleOrderPlugin", "Insert_After_plm", errMsg);
                    return false;
                }
                bool js;

                js = GetCustJsPlm(login.get_cAcc_Id(), ref dombody, 0);

                return js;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("SaleOrderPlugin", "Insert_After_plm", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="accid"></param>
        /// <param name="dombody"></param>
        /// <param name="operation"></param>
        /// <returns></returns>
        private bool GetCustJsPlm(string accid, ref MSXML2.IXMLDOMDocument2 dombody, int operation)
        {
            string cinvcode;
            decimal iquantity, itaxunitprice;
            try
            {
                var datatable = Common.GetPlmUrl(constr, accid).Tables[0];
                var datarow = datatable.Rows[0];
                url = datarow[1].ObjToString() + "IF_03?";

                MSXML2.IXMLDOMNodeList nodeList = dombody.selectNodes("//rs:data/z:row");
                MSXML2.IXMLDOMNode node = null;

                for (int i = 0; i < nodeList.length; i++)
                {
                    node = nodeList.nextNode();
                    //物料
                    cinvcode = Convert.ToString(node.attributes.getNamedItem("cinvcode").nodeValue);
                    //数量
                    iquantity = Convert.ToDecimal(node.attributes.getNamedItem("iquantity").nodeValue);
                    //单价
                    itaxunitprice = Convert.ToDecimal(node.attributes.getNamedItem("itaxunitprice").nodeValue);



                    Dictionary<string, string> js = new Dictionary<string, string>();
                    js.Add("itemid", cinvcode);
                    //js.Add("orgcode", accid);

                    var result = HttpHelper.PostDataToServerDic(url, js, "application/x-www-form-urlencoded");
                    var apiresult = Common.DeserializeObject<PlmRequest>(result);
                    if (apiresult.SUC_FLG != 0)
                    {
                        string errMsg = apiresult.Error_Message;
                        throw new Exception(errMsg);
                    }
                    //Plmprices pp = Common.DeserializeObject<Plmprices>(apiresult.prices.ToJson());
                    if (apiresult.prices != null)
                    {
                        foreach (Plmprice item in apiresult.prices)
                        {
                            if (item == null)
                            {
                                return true;
                            }
                            if (iquantity <= item.count)
                            {
                                if (itaxunitprice < item.price)
                                {
                                    return false;
                                }
                            }
                        }
                    }

                }

                return true;
            }
            catch (Exception e)
            {
                DebugWriteLog.WriteLine("SaleOrderPlugin", "Insert_After_plm", e);
                throw e;
            }
        }

        /// <summary>
        /// 审核与变更后审核
        /// </summary>
        /// <param name="domhead"></param>
        /// <param name="dombody"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public bool Update_After(ref MSXML2.IXMLDOMDocument2 domhead, ref MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            try
            {

                MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

                //从上下文获取U8Login对象
                U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
                if (login != null)
                    constr = login.UFDataConnstringForNet;

                if (string.IsNullOrEmpty(constr))
                {
                    errMsg = "SaleOrderPlugin，Update_After，获取连接串失败";
                    DebugWriteLog.WriteLine("SaleOrderPlugin", "Update_After", errMsg);
                    return false;
                }
                string accid = login.get_cAcc_Id();
                MSXML2.IXMLDOMNode tmphead = domhead.selectSingleNode("//z:row");

                int dlid = Convert.ToInt32(tmphead.attributes.getNamedItem("id").nodeValue.ObjToString());//发货单id            
                string cVerifier = "";
                if (tmphead.attributes.getNamedItem("cverifier") != null) //审核人
                {
                    cVerifier = tmphead.attributes.getNamedItem("id").nodeValue.ToString();
                }

                String js;
                int operation = 0;
                if (!string.IsNullOrEmpty(cVerifier))
                {
                    operation = 2;
                }

                js = GetCustJs(accid, dlid, operation);
                if (js == null)
                {
                    return true;
                }

                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    DebugWriteLog.WriteLine("SaleOrderPlugin", "Update_After", errMsg);
                    throw new Exception(errMsg);
                    //return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("SaleOrderPlugin", "Update_After", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }


        /// <summary>
        /// 打开事件
        /// </summary>
        /// <param name="domhead"></param>
        /// <param name="dombody"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public bool Open_After(ref MSXML2.IXMLDOMDocument2 domhead, ref MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            try
            {

                MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

                //从上下文获取U8Login对象
                U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
                if (login != null)
                    constr = login.UFDataConnstringForNet;

                if (string.IsNullOrEmpty(constr))
                {
                    errMsg = "SaleOrderPlugin，Update_After，获取连接串失败";
                    DebugWriteLog.WriteLine("SaleOrderPlugin", "Update_After", errMsg);
                    return false;
                }
                string accid = login.get_cAcc_Id();
                MSXML2.IXMLDOMNode tmphead = domhead.selectSingleNode("//z:row");

                int dlid = Convert.ToInt32(tmphead.attributes.getNamedItem("id").nodeValue.ObjToString());//发货单id         

                String js;
                int operation = 4;


                js = GetCustJs(accid, dlid, operation);
                if (js == null)
                {
                    return true;
                }

                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    DebugWriteLog.WriteLine("SaleOrderPlugin", "Update_After", errMsg);
                    throw new Exception(errMsg);
                    //return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("SaleOrderPlugin", "Update_After", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }


        /// <summary>
        /// 关闭事件
        /// </summary>
        /// <param name="domhead"></param>
        /// <param name="dombody"></param>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public bool Close_After(ref MSXML2.IXMLDOMDocument2 domhead, ref MSXML2.IXMLDOMDocument2 dombody, ref string errMsg)
        {
            //获取插件上下文
            bool bresult = true;
            try
            {

                MomCallContext ctx = MomCallContextCache.Instance.CurrentMomCallContext;

                //从上下文获取U8Login对象
                U8Login.clsLogin login = ctx.U8Login as U8Login.clsLogin;
                if (login != null)
                    constr = login.UFDataConnstringForNet;

                if (string.IsNullOrEmpty(constr))
                {
                    errMsg = "SaleOrderPlugin，Update_After，获取连接串失败";
                    DebugWriteLog.WriteLine("SaleOrderPlugin", "Update_After", errMsg);
                    return false;
                }
                string accid = login.get_cAcc_Id();
                MSXML2.IXMLDOMNode tmphead = domhead.selectSingleNode("//z:row");

                int dlid = Convert.ToInt32(tmphead.attributes.getNamedItem("id").nodeValue.ObjToString());//发货单id     

                String js;
                int operation = 3;

                js = GetCustJs(accid, dlid, operation);
                if (js == null)
                {
                    return true;
                }

                var result = HttpHelper.PostDataToServer(url, js);
                var apiresult = Common.DeserializeObject<ApiResponse>(result);
                if (apiresult.successful != 0)
                {
                    errMsg = apiresult.message;
                    DebugWriteLog.WriteLine("SaleOrderPlugin", "Update_After", errMsg);
                    throw new Exception(errMsg);
                    //return false;
                }

                return true;
            }
            catch (Exception ex)
            {
                DebugWriteLog.WriteLine("SaleOrderPlugin", "Update_After", ex);
                bresult = false;
                errMsg = ex.Message;
            }
            return bresult;
        }

        private string GetCustJs(string accid, int id, int operation)
        {
            DebugWriteLog.WriteLine("销售订单接口", "ccode", "id=" + id);

            try
            {
                var datatable = Common.GetUrl(constr, accid).Tables[0];
                if (datatable == null)
                {
                    DebugWriteLog.WriteLine("销售订单接口", "GetUrl", "Nopermission");
                    return "Nopermission";
                }
                var datarow = datatable.Rows[0];
                if (datatable == null)
                {
                    DebugWriteLog.WriteLine("销售订单接口", "GetUrl", "datarow Nopermission");
                    return "Nopermission";
                }
                url = datarow[1] + "saleOrder";
                DebugWriteLog.WriteLine("销售订单接口地址:" + url);
                UFIDA.U8.DB.Model.SO_SOMain model = UFIDA.U8.DB.DAL.SO_SOMain.GetModel(id.ObjToInt32(), constr);
                if (model == null || model.SO_SODetailss == null)
                {
                    DebugWriteLog.WriteLine("销售订单接口", "table", " Nopermission");
                    return "Nopermission";
                }
                List<SaleOrder> mlist = new List<SaleOrder>();
                SaleOrder receive = new SaleOrder();
                receive.billcode = model.cSOCode;
                receive.billdate = model.dDate;
                receive.createdby = model.cMaker;
                receive.customercode = model.cCusCode;
                receive.customername = model.cCusName;
                receive.address = model.cCusOAddress;
                receive.UpperLimit = model.cDefine7;
                receive.cCrmPersonCode = model.ccuspersoncode;
                receive.cCrmPersonName = model.ccusperson;
                receive.cCrmPersonPhone = model.cmobilephone;


                receive.pobillcode = model.cDefine11;
                receive.bodys = new List<saleorders>();

                foreach (var item in model.SO_SODetailss)
                {
                    #region 原有字段
                    saleorders detail = new saleorders();
                    detail.material = item.cInvCode;
                    detail.cinvname = item.cInvName;
                    UFIDA.U8.DB.Model.Inventory_extradefine inv = UFIDA.U8.DB.DAL.Inventory_extradefine.GetModel(item.cInvCode, constr);
                    if (inv != null)
                    {
                        detail.partno = inv.cidefine4;
                    }

                    detail.rowid = item.iRowNo.ObjToInt32();
                    detail.Qty = item.iQuantity;
                    detail.PerShipDate = item.dPreDate;
                    receive.bodys.Add(detail);

                    #endregion

                    mlist.Add(receive);
                }


                ApiRequest req = new ApiRequest();
                req.data = mlist;
                req.orgcode = accid;
                req.primarykey = id.ToString();
                req.operation = operation;

                DebugWriteLog.WriteLine("销售订单接口", "抛出参数", req.ToJson());
                return req.ToJson();

            }
            catch (Exception e)
            {
                DebugWriteLog.WriteLine("销售订单接口", "异常", e);
                throw e;
            }
        }

        private Dictionary<string, string> GetCustDic(string accid, int id, int operation)
        {
            DebugWriteLog.WriteLine("销售订单接口", "ccode", "id=" + id);

            try
            {

                UFIDA.U8.DB.Model.SO_SOMain model = UFIDA.U8.DB.DAL.SO_SOMain.GetModel(id.ObjToInt32(), constr);
                if (model == null)
                {
                    DebugWriteLog.WriteLine("销售订单接口", "table", " Nopermission");
                    return null;
                }
                if (!string.IsNullOrEmpty(model.cDefine8) && model.cDefine8.Equals("是"))
                {
                    if (string.IsNullOrEmpty(model.cDefine10))
                    {
                        throw new Exception("内部协同订单，最终客户不能为空");
                    }
                    UFIDA.U8.DB.Model.Customer cus = UFIDA.U8.DB.DAL.Customer.GetModel(model.cCusCode, constr);
                    if (cus == null || string.IsNullOrEmpty(cus.cCusDefine1))
                    {
                        throw new Exception("销售订单接口, 客户档案设置有误，未设置对应orgcode");
                    }

                    url = cus.cCusDefine7;
                    if (string.IsNullOrEmpty(url))
                    {
                        throw new Exception("销售订单接口, 客户档案设置有误,未配置接口地址");
                    }
                    url = cus.cCusDefine7 + "Sync_SOPO/Create?";

                    Dictionary<string, string> dic = new Dictionary<string, string>();
                    dic.Add("orgcode", cus.cCusDefine1);
                    dic.Add("operation", operation.ToString());
                    dic.Add("primarykey", model.cSOCode);
                    dic.Add("csource", accid);
                    dic.Add("data", model.ToJson());


                    DebugWriteLog.WriteLine("销售订单接口", "抛出参数", model.ToJson());
                    return dic;
                }
                else
                {
                    return null;
                }

            }
            catch (Exception e)
            {
                DebugWriteLog.WriteLine("销售订单接口", "异常", e);
                throw e;
            }
        }

    }
}
